<template>
  <el-container>
    <!-- 占位 -->
    <el-col :span="2"></el-col>

    <!-- 头部显示开始 -->
    <el-col :span="20">
      <el-row style="margin-top: 20px">
        <el-image :src="headImgUrl" class="headImg"></el-image>
        <el-row style="float: left">
          <p class="headText">{{ queryPictureDTO.tag || "所有图片" }}</p>
          <p class="headTotalText">共 {{ this.pictureTotal }} 张图片</p>
        </el-row>
      </el-row>
      <!-- 头部显示结束 -->

      <!-- 排序选择开始 -->
      <el-select
        v-model="queryPictureDTO.desc"
        placeholder="默认排序"
        style="margin-top: 30px; border-style: none"
        @change="searchBySort"
      >
        <el-option key="1" label="按时间最新发布排序" :value="true" />
        <el-option key="2" label="按时间最早发布排序" :value="false" />
      </el-select>
      <!-- 排序选择结束 -->
      <el-link style="" type="info" @click="searchWithOutTag()">
        &nbsp;不限制标签
      </el-link>
      <el-link style="float: right" type="info" @click="toRouter('/tag')"
        >查看更多标签 >></el-link
      >

      <!--  图片显示开始 -->
      <transition
        name="fade"
        appear
        enter-active-class="animate__animated animate__fadeInUp"
        leave-active-class="animate__animated animate__fadeOut"
        duration="1500"
      >
        appear>
        <el-row v-show="petPictureArray.length > 0">
          <!-- 第一列  -->
          <el-col :span="6">
            <div v-for="(item, index) in petPictureArrayA" :key="'a' + index">
              <!-- 鼠标聚焦信息, 显示图片描述、标签和创建时间 -->
              <el-popover
                placement="right-start"
                title="标签: 小猫咪举高高"
                width="200"
                trigger="hover"
              >
                <el-image
                  slot="reference"
                  :src="item.imgUrl"
                  class="image-pet"
                  :preview-src-list="petPictureArray"
                  fit="contain"
                  :initial-index="item.index"
                  lazy
                />

                <div>
                  <hr />
                  {{ item.detail }}
                  <br />
                  <small style="float: right">{{
                    item.createTime | formatDate
                  }}</small>
                </div>
              </el-popover>
            </div>
          </el-col>
          <!-- 第二列 -->
          <el-col :span="6">
            <div v-for="(item, index) in petPictureArrayB" :key="'b' + index">
              <!-- 鼠标聚焦信息, 显示图片描述、标签和创建时间 -->
              <el-popover
                placement="right-start"
                title="标签: 小猫咪举高高"
                width="200"
                trigger="hover"
              >
                <el-image
                  slot="reference"
                  :src="item.imgUrl"
                  class="image-pet"
                  :preview-src-list="petPictureArray"
                  :initial-index="item.index"
                  fit="contain"
                  lazy
                />

                <div>
                  <hr />
                  {{ item.detail }}
                  <br />
                  <small style="float: right">{{
                    item.createTime | formatDate
                  }}</small>
                </div>
              </el-popover>
            </div>
          </el-col>

          <!-- 第三列 -->
          <el-col :span="6">
            <div v-for="(item, index) in petPictureArrayC" :key="'c' + index">
              <!-- 鼠标聚焦信息, 显示图片描述、标签和创建时间 -->
              <el-popover
                placement="right-start"
                title="标签: 小猫咪举高高"
                width="200"
                trigger="hover"
              >
                <el-image
                  slot="reference"
                  :src="item.imgUrl"
                  class="image-pet"
                  :preview-src-list="petPictureArray"
                  :initial-index="item.index"
                  fit="contain"
                  lazy
                />

                <div>
                  <hr />
                  {{ item.detail }}
                  <br />
                  <small style="float: right">{{
                    item.createTime | formatDate
                  }}</small>
                </div>
              </el-popover>
            </div>
          </el-col>

          <!-- 第四列 -->
          <el-col :span="6">
            <div v-for="(item, index) in petPictureArrayD" :key="'d' + index">
              <!-- 鼠标聚焦信息, 显示图片描述、标签和创建时间 -->
              <el-popover
                placement="right-start"
                title="标签: 小猫咪举高高"
                width="200"
                trigger="hover"
              >
                <el-image
                  slot="reference"
                  :src="item.imgUrl"
                  class="image-pet"
                  :preview-src-list="petPictureArray"
                  :initial-index="item.index"
                  fit="contain"
                  lazy
                />

                <div>
                  <hr />
                  {{ item.detail }}
                  <br />
                  <small style="float: right">{{
                    item.createTime | formatDate
                  }}</small>
                </div>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </transition>
      <!-- 图片显示结束 -->

      <el-row v-if="petPictureArray.length == 0 && hadLoadData">
        <h1 style="text-align: center; font-weight: 100">
          抱歉，没有搜索到任何相关的图片
        </h1>
      </el-row>
    </el-col>

    <!-- 占位 -->
    <el-col :span="2"></el-col>
  </el-container>
</template>

<script>
import imageUtil from "@/utils/imageUtil";
import { dateUtilFormat } from "@/utils/dateUtil";
import pictureApi from "@/api/picture.js";

export default {
  data() {
    return {
      // 图片数量统计
      pictureTotal: 0,
      // 是否放大图片
      openBigPicture: false,
      // 标记是否加载完数据
      hadLoadData: false,
      // 查询图片
      queryData: {
        detail: "", // 图片关键字
        tag: "", // 图片标签
        desc: false, // 是否按时间降序, 默认升序（即按最早发布），
        startIndex: 0, // 从第几条记录开始
      },
      // 头部的图片
      headImgUrl: require("@/assets/cat1.jpg"), // 默认图片

      // 宠物图片
      petPictureArray: [],
      petPictureArrayA: [
        // { url: require("@/assets/dog1.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat2.jpg"), detail: "宠物" },
        // { url: require("@/assets/dog2.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat3.jpg"), detail: "宠物" },
      ],
      petPictureArrayB: [
        // { url: require("@/assets/dog3.jpg"), detail: "宠物" },
        // { url: require("@/assets/dog1.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat2.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat3.jpg"), detail: "宠物" },
      ],
      petPictureArrayC: [
        // { url: require("@/assets/dog3.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat1.jpg"), detail: "宠物" },
        // { url: require("@/assets/dog1.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat2.jpg"), detail: "宠物" },
      ],
      petPictureArrayD: [
        // { url: require("@/assets/cat2.jpg"), detail: "宠物" },
        // { url: require("@/assets/dog2.jpg"), detail: "宠物" },
        // { url: require("@/assets/cat3.jpg"), detail: "宠物" },
        // { url: require("@/assets/dog3.jpg"), detail: "宠物" },
      ],
    };
  },
  created() {
    this.queryData.detail = this.$route.query.detail || "";
    this.queryData.tag = this.$route.query.tag || "";
    this.queryData.desc = this.$route.query.desc === "true";
    this.queryData.startIndex = parseInt(this.$route.query.startIndex) || 0;
  },
  mounted() {
    // 计算所有的图片信息
    // MOCK数据: this.petPictureArray = imageUtil.getImageUrlByArray(this.petPictureArrayA);
    // 获取图片资源
    this.loadData();
  },
  methods: {
    /**
     * 根据条件统计图片数量，条件为this.queryPictureDTO
     */
    countPictureByCondition() {
      pictureApi.countPicture(this.queryPictureDTO).then((resp) => {
        // 记录请求到的图片信息
        this.pictureTotal = resp.data;
      });
    },
    /**
     * 根据条件查询图片，这里的条件是 this.queryPictureDTO
     */
    queryPictureByCondition() {
      // 更新URL
      // 首先初始化数据
      this.petPictureArray = [];
      this.petPictureArrayA = [];
      this.petPictureArrayB = [];
      this.petPictureArrayC = [];
      this.petPictureArrayD = [];
      pictureApi.queryPicture(this.queryPictureDTO).then((picutreList) => {
        // 记录请求到的图片信息
        this.petPictureArray = picutreList.data;
        // 执行轮训分配算法，将一个数组分为四个数组
        for (let i = 0; i < this.petPictureArray.length; i++) {
          const pic = this.petPictureArray[i];
          // 根据元素在原始数组中的索引，将元素依次分配到四个数组中
          switch (i % 4) {
            case 0:
              this.petPictureArrayA.push({ ...pic, index: i });
              break;
            case 1:
              this.petPictureArrayB.push({ ...pic, index: i });
              break;
            case 2:
              this.petPictureArrayC.push({ ...pic, index: i });
              break;
            case 3:
              this.petPictureArrayD.push({ ...pic, index: i });
              break;
            default:
              break;
          }
        }
        // 提取出URL
        this.petPictureArray = imageUtil.getImageUrlByArray(
          this.petPictureArray
        );
        // 设置头部图片，默认为第一张
        this.headImgUrl = this.petPictureArray[0];
        // 检查处理后的图片信息是否正确
        // console.log('AAAAAA', this.petPictureArrayA)
        // console.log('BBBBBB', this.petPictureArrayB)
        // console.log('CCCCCC', this.petPictureArrayC)
        // console.log('DDDDDD', this.petPictureArrayD)
        // 标记已加载完数据, 更新 DOM
        this.hadLoadData = true;
      });
    },

    /**
     * 加载数据
     */
    loadData() {
      this.hadLoadData = false
      // 根据搜索条件查询图片数量
      this.countPictureByCondition();
      // 根据搜索条件查询图片信息
      this.queryPictureByCondition();
    },
    /**
     * 跳转路由
     */
    toRouter(url) {
      this.$router.push(url);
    },

    /**
     * 去掉标签后查询
     */
    searchWithOutTag() {
      this.queryData.tag = "";

      this.$router.replace({
        path: "/search",
        query: { ...this.queryPictureDTO, t: new Date().getTime() },
      });
      this.loadData();
    },

    /**
     * 根据搜索条件排序
     */
    searchBySort() {
      // 去掉空参数
      const query = {};

      if (this.queryData.detail !== "") query.detail = this.queryData.detail;
      if (this.queryData.tag !== "") query.tag = this.queryData.tag;

      query.desc = this.queryData.desc;
      query.startIndex = 0;
      this.$router.replace({
        path: "/search",
        query: { ...query, t: new Date().getTime() },
      });
      this.loadData();
    },
  },
  computed: {
    // 搜索条件
    // 搜索条件
    queryPictureDTO() {
      return this.queryData;
    },
  },
  watch: {
    queryPictureDTO: {
      handler(newVal) {
        this.$router.replace({ path: "/search", query: newVal });
      },
      deep: true,
    },
  },
  filters: {
    formatDate(value) {
      return dateUtilFormat(value);
    },
  },
};
</script>

<style>
/* 头部图片 */
.headImg {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  float: left;
}
/* 头部标题 */
.headText {
  font-size: 1.2em;
  text-indent: 1.1em;
  margin: 10px;
}
/* 图片统计 */
.headTotalText {
  text-indent: 2.2em;
  font-size: 0.9em;
  color: gray;
}
/* 宠物图片 */
.image-pet {
  width: 95%;
  height: auto;
  border-radius: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
}

/* 宠物图片的包装 */
.image-pet-wrapper {
  width: calc(33.33% - 20px); /* 每列宽度固定为 1/3，减去间距 */
  margin-right: 20px; /* 设置列间距 */
  margin-bottom: 20px; /* 设置行间距 */
}
/* 宠物图片容器 */
.image-pet-container {
  display: flex;
  flex-wrap: wrap;
}
</style>